import { defineStore } from 'pinia'
import { ref } from 'vue'

/**
 * 购物车商品接口
 */
export interface CartItem {
  id: number
  name: string
  price: number
  image: string
  quantity: number
}

/**
 * 购物车状态管理
 * 性能优化：使用Pinia进行状态管理，支持持久化存储
 */
export const useCartStore = defineStore('cart', () => {
  // 购物车商品列表
  const items = ref<CartItem[]>([])
  
  // 获取购物车商品总数
  const getTotalItems = () => {
    return items.value.reduce((total, item) => total + item.quantity, 0)
  }
  
  // 获取购物车总金额
  const getTotalPrice = () => {
    return items.value.reduce((total, item) => total + item.price * item.quantity, 0)
  }
  
  // 添加商品到购物车
  const addToCart = (product: CartItem) => {
    const existingItem = items.value.find(item => item.id === product.id)
    
    if (existingItem) {
      existingItem.quantity += product.quantity
    } else {
      items.value.push({ ...product })
    }
  }
  
  // 更新商品数量
  const updateQuantity = (id: number, quantity: number) => {
    const item = items.value.find(item => item.id === id)
    if (item) {
      item.quantity = Math.max(0, quantity)
      if (item.quantity === 0) {
        removeFromCart(id)
      }
    }
  }
  
  // 从购物车移除商品
  const removeFromCart = (id: number) => {
    const index = items.value.findIndex(item => item.id === id)
    if (index > -1) {
      items.value.splice(index, 1)
    }
  }
  
  // 清空购物车
  const clearCart = () => {
    items.value = []
  }
  
  // 检查商品是否在购物车中
  const isInCart = (id: number) => {
    return items.value.some(item => item.id === id)
  }
  
  return {
    items,
    getTotalItems,
    getTotalPrice,
    addToCart,
    updateQuantity,
    removeFromCart,
    clearCart,
    isInCart
  }
}) 